package com.juc.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock不会像sync一样自动释放锁， 必须在finally中释放
 *
 * @author mobai
 * @since 2021/3/10 17:31
 */
public class MustUnLock {

    public static final ExecutorService executorService = Executors.newFixedThreadPool(5);

    private static final Lock lock = new ReentrantLock();

    private static int a = 1;

    public static void main(String[] args) {


        final LockTest lockTest=new LockTest();
        Runnable r=()->{
            for (int i = 0; i < 100; i++) {
                lockTest.incr();
            }
        };
        for (int i = 0; i < 5; i++) {
            executorService.execute(r);
        }


    }

    static class LockTest {
        private int a;


        public void incr() {
            lock.lock();
            a++;
            int a = 10 / 0;
            //此处不会释放锁
            lock.unlock();
        }

    }

    static class Printer{

        public void print(String name) throws InterruptedException {
            lock.lock();
            try {
                for (int i = 0; i < name.length(); i++) {
                    Thread.sleep(150);
                    System.out.println(name.charAt(i));
                }
            }finally {
                lock.unlock();
            }

        }

        public static void main(String[] args) {
            Printer printer=new Printer();
            new Thread(()-> {
                try {
                    printer.print("hello");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();

            new Thread(()-> {
                try {
                    printer.print("nihao");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();




        }

    }



}
